﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MdcService.Configuration;
using MdcService.DataAccess;
using MdcService.Log;
using MdcService.Static;
using MdcService.Structure;
using MdcService.Structure.Enum;

namespace MdcService.Service
{
    public class RecordingService:IService
    {
        private ConfigurationService _configurations;
        private IRealTimeDataAccess<MachineValue> _realtimeDataAccess;
        private HistoryDbService _historyDataAccess;
        private RunningContext _runningContext;
        private Timer _historyStoreTimer;
        private ILogging _logging;

        public event EventHandler<EventArgs> Started;
        public event EventHandler<EventArgs> Stopped;



        public RecordingService(ConfigurationService configurations, IRealTimeDataAccess<MachineValue> realtimeDataAccess, HistoryDbService historyDataAccess, RunningContext runningContext, ILogging logging)
        {
            _configurations = configurations;
            _realtimeDataAccess = realtimeDataAccess;
            _historyDataAccess = historyDataAccess;
            this._runningContext = runningContext;
            _logging = logging;


            _historyStoreTimer = new Timer(HistoryTimerCallback, null, Timeout.Infinite,
                configurations.Configuration.HistoryCollectionInterval);

            
        }

     

        public void Start()
        {
            if (_runningContext.RecordingServiceState == ServiceState.Running) return;

            _historyStoreTimer.Change(0, _configurations.Configuration.HistoryCollectionInterval);
            _runningContext.RecordingServiceState = ServiceState.Running;
            Started?.Invoke(this, new EventArgs());

        }

        public void Stop()
        {
            if (_runningContext.RecordingServiceState == ServiceState.Stopped) return;

            _historyStoreTimer.Change(Timeout.Infinite, _configurations.Configuration.HistoryCollectionInterval);
            _runningContext.RecordingServiceState = ServiceState.Stopped;
            Stopped?.Invoke(this, new EventArgs());

        }

   
        private void HistoryTimerCallback(object state)
        {
            _configurations.MachineDefinitions.ForEach(i =>
            {
                var x = _realtimeDataAccess.Select(i.Id);
                if(x.Count>0) _historyDataAccess.Insert(x);
            });
        }
    }
}
